//
//  ST_ConversionHistoryViewController.swift
//  btvideo
//
//  Created by mac on 2020/10/12.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON
import SwiftyUserDefaults


class ST_ConversionHistoryViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("兑换记录")
        
      
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        request_data()
    }
    
    fileprivate func empty_view_handle(){
        
        if self.data_array.count < 1{
            
            let control = ST_BTEmptyView.init(title: "赚点\(Defaults[.PandaStr])玩的更嗨哦~", imageName: ST_ImageUtils.imageName("首页_img_活跃(空)")!)
            
            self.collectionView.show_bitian_empty(view: control)
            
        }else{
            self.collectionView.hidden_bitian_empty_view()
        }
    }
    
    
    fileprivate func request_data(){
        
        
        currentPage += 1
        
        JVrequest(PH.exchangeLogByIncomeApi,parameters: ["page":currentPage,"size":25], success: { (json) in
            
            let array = json["data"].arrayValue.map { (itemJson) -> ST_ExchangeLogModel in
                return ST_ExchangeLogModel.init(fromJson: itemJson)
            }
            
            if self.currentPage == 1{
                self.data_array = array
            }else{
                self.data_array += array
            }
            
            self.empty_view_handle()
            
            self.collectionView.reloadData {
                self.load_more_option_style(tableView: self.collectionView, count: array.count, pageSize: 25) {
                    
                    self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
            }
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
    }
    
//    MARK: - Properties
    fileprivate lazy var currentPage = 0
    
    fileprivate lazy var data_array = [ST_ExchangeLogModel]()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
      let controlLayout = UICollectionViewFlowLayout()
        controlLayout.itemSize = CGSize.init(width: ScreenWidth, height: 68 )
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
       return controlLayout
   }()
       
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_ConversionHistoryCell.self)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom, right: 0)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
}

extension ST_ConversionHistoryViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ConversionHistoryCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.row]
        
        return cell
    }
    
    
    
}


//MARK: - Cell
class ST_ConversionHistoryCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .white
        
        
        contentView.addSubview(icon_image_view)
        contentView.addSubview(key_label)
        contentView.addSubview(value_label)
        contentView.addSubview(right_label)
        
        
        
        icon_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(32)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(15)
        }
        
        key_label.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15)
            make.left.equalTo(icon_image_view.snp.right).offset(15)
            make.height.equalTo(20)
        }
        
        
        value_label.snp.makeConstraints { (make) in
            make.left.equalTo(key_label).offset(3)
            make.top.equalTo(key_label.snp.bottom).offset(1)
            make.height.equalTo(15)
        }
        
        right_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalToSuperview()
        }
        
        contentView.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(62)
            make.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var icon_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        return control
    }()
    
    
    fileprivate lazy var key_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#3A3A3A")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()

    fileprivate lazy var value_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#CDD0DA")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var right_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    fileprivate lazy var lineView:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        return control
    }()
    
    
    var model:ST_ExchangeLogModel?{
        didSet{
            
            guard let m = model else { return }
            
            icon_image_view.pin_setImage(from: m.image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            key_label.text = m.mallName
            
            value_label.text = m.createTime
            
            right_label.text = "-\(m.mallIntegral)\(Defaults[.PandaStr])"
            
        }
    }
}



//MARK: - Model

class ST_ExchangeLogModel : NSObject{

    var approveRemark : String
    var createTime : String
    var image : String
    var mallIntegral : Int
    var mallMoney : Int
    var mallName : String
    var mallType : Int
    var state : Int

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        approveRemark = json["approve_remark"].stringValue
        createTime = json["create_time"].stringValue
        image = json["image"].stringValue
        mallIntegral = json["mall_integral"].intValue
        mallMoney = json["mall_money"].intValue
        mallName = json["mall_name"].stringValue
        mallType = json["mall_type"].intValue
        state = json["state"].intValue
        super.init()
    }
}
